import { Component, OnInit } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import { NzModalService, NzMessageService } from 'ng-zorro-antd';
import { ApiService } from '../../../core/api.service';
import { LocalStorage } from '@core/local.storage';
import { environment } from '../../../../environments/environment';
import { HttpHeaders } from '@angular/common/http';
import { StatusFollowService } from '@core/statusFollow.service';
import { DatePipe } from '@angular/common';
import { forkJoin } from 'rxjs';

@Component({
  selector: 'app-lssd.component',
  templateUrl: './lssd.component.html',
  styleUrls: ['./lssd.component.less']
})

export class LssdComponent implements OnInit {
  responseHeaders = new HttpHeaders().set('Content-Type', 'application/json;charset=UTF-8');
  tableData: any = [];
  pageTotal = 0;
  pageIndexTable = 1;
  selectedValue = '50';
  allChecked = false;
  indeterminate = false;
  queryParam: any = {};
  mapOfCheckedId: any = {};
  modalPanel = {
    style: {
      width: '1000px'
    }
  };
  lockHeadScroll = { y: window.innerHeight - 350 + 'px' };
  dropdownStyle = { height: '200px' };
  userInfo = JSON.parse(this.ls.get('loginInfo'));

  status = ['修改中', '已申请', '已签发', '已驳回'];

  addVisible: boolean;
  addData: any = {};
  tableLoading: boolean;
  editData: any = {};
  editVisible: boolean;
  detailData: any = {};
  detailVisible: boolean;
  cjList: any = [];
  cjList_filter: any = [];
  gqList: any = [];
  gqList_filter: any = [];
  slrList: any = [];
  slrList_filter: any = [];
  shouldEdit = false;

  constructor(
    // private activatedRoute: ActivatedRoute,
    private apiService: ApiService,
    private http: _HttpClient,
    public ls: LocalStorage,
    public msg: NzMessageService,
    private datePipe: DatePipe,
    private modalService: NzModalService,
    // private router: Router,
    // private reuseTabService: ReuseTabService,
    private statusFollowService: StatusFollowService,
  ) { }

  ngOnInit() {
    this.initCmp();
    this.readyload(this.pageIndexTable, this.selectedValue);
  }

  statusFollow(data) {
    return this.statusFollowService.init('6', data);
  }

  getHeight() {
    return window.innerHeight - 350;
  }

  // 分页数量
  selectedChange() {
    this.readyload(this.pageIndexTable, this.selectedValue);
  }

  rowChangeTable(ev) {
    this.pageIndexTable = ev;
    this.readyload(this.pageIndexTable, this.selectedValue);
  }

  refreshStatus(): void {
    const tableData = this.tableData;
    if (tableData.length) {
      const allChecked = this.tableData.every(value => value.checked == true);
      const allUnChecked = this.tableData.every(value => !value.checked);
      this.allChecked = allChecked;
      this.indeterminate = (!allChecked) && (!allUnChecked);
    }
  }

  // 全选
  checkAll(value: boolean): void {
    this.tableData.forEach(data => {
      if (!data.disabled) {
        data.checked = value;
        this.mapOfCheckedId[data.nId] = value;
      }
    });
    this.refreshStatus();
  }


  initDate() {
    const _date = new Date();
    this.queryParam._sDate = _date;
    this.queryParam._eDate = _date;
    this.addData._dtDate = _date;
  }

  initCmp() {
    this.initDate();
    this.getWorkshop();
  }

  getCheckIds(mapOfCheckedId) {
    const ids = [];
    for (const key in mapOfCheckedId) {
      if (mapOfCheckedId.hasOwnProperty(key)) {
        const v = mapOfCheckedId[key];
        if (v) {
          ids.push(key);
        }
      }
    }
    return ids;
  }

  getTableDataById(id, tableData) {
    return tableData.find(row => (row.nId + '') == (id + ''));
  }

  getTableDataByIds(ids, tableData) {
    return tableData.filter(row => ids.includes(row.nId + ''));
  }

  selfCheck(row) {
    return row.vcReqdep == this.userInfo.VC_ORG$ID;
  }

  editCheck() {
    const optName = '申请上道';
    const optStatus = ['0', '3']; // 允许进行操作的状态
    // const ids = this.getCheckIds(this.mapOfCheckedId);
    // const data = this.getTableDataById(ids[0], this.tableData);
    const tableData = this.tableData;
    if (!tableData.length) {
      this.msg.warning(`当前无可操作数据`);
      return;
    }
    const data = tableData.filter(data => data.checked);
    if (!data.length) {
      this.msg.warning(`请勾选条目进行${optName}操作`);
      return;
    }
    if (data.length > 1) {
      this.msg.warning(`最多勾选一个条目进行${optName}操作`);
      return;
    }
    // if (this.userInfo.N_LEVEL == 10) {
    //   if (!this.selfCheck(data)) {
    //     this.msg.warning(`您只能操作执行部门为${this.userInfo.VC_ORG$NAME}的条目`);
    //     return;
    //   }
    // }
    if (!optStatus.includes(data[0].vcStatus)) {
      this.msg.warning(`勾选的条目属于${this.status[data.vcStatus] || '未定义'}状态，您不可${optName}此状态的条目`);
      return;
    } else if (data[0].vcType == '0') {
      this.msg.warning(`勾选的条目属于下道申请状态，您不可${optName}此状态的条目`);
      return;
    }
    this.editModal(data[0]);
  }

  /**
   * 驳回
   */
  bohui(ids) {
    // return;
    this.modalService.confirm({
      nzTitle: `<i>确认</i>`,
      nzWidth: '600',
      nzContent: `<b>确认驳回吗?</b>`,
      nzOnOk: () => {
        const url = environment.project + '/ymTTempworkinfo/rejectAplly';
        this.http.post(url, ids).subscribe((res: any) => {
          if (res.msg === 'Ok') {
            this.msg.success('驳回' + '成功', { nzDuration: 1000 });
            this.readyload(this.pageIndexTable, this.selectedValue);
          } else {
            this.msg.error('驳回失败', { nzDuration: 1000 });
          }
        });
      }
    });

  }

  bohuiCheck() {
    const tableData = this.tableData;
    if (!tableData.length) {
      this.msg.warning(`当前无可操作数据`);
      return;
    }
    const ids = tableData.filter(data => data.checked).map(data => data.nId);
    if (!ids.length) {
      this.msg.warning(`请勾选条目进行驳回操作`);
      return;
    }
    const datas = this.getTableDataByIds(ids, tableData);
    let hasUnSaveable = false; // 存在状态错误
    let unSaveAbleStatus = '';
    let hasUnSaveable2 = false; // 存在下道申请
    datas.forEach(data => {
      if (['0', '2', '3'].includes(data.vcStatus)) {
        hasUnSaveable = true;
        unSaveAbleStatus = data.vcStatus;
      } else if (data.vcType == '0') {
        hasUnSaveable2 = true;
      }
    });
    if (hasUnSaveable) {
      this.msg.warning(`勾选的条目中存在${this.status[unSaveAbleStatus] || '未定义'}状态，您不可驳回此状态的条目`);
      return;
    }
    if (hasUnSaveable2) {
      this.msg.warning(`勾选的条目进行了或者处于下道申请状态，您不可驳回此状态的条目`);
      return;
    }
    this.bohui(ids);
  }

  /**
   * 签发
   * 调度不受申请部门的限制
   */
  qianfaCheck() {
    // let optName = '签发';
    // let optStatus = '2';
    // const ids = this.getCheckIds(this.mapOfCheckedId);
    const tableData = this.tableData;
    if (!tableData.length) {
      this.msg.warning(`当前无可操作数据`);
      return;
    }
    const ids = tableData.filter(data => data.checked).map(data => data.nId);
    if (!ids.length) {
      this.msg.warning(`请勾选条目进行签发操作`);
      return;
    }

    const datas = this.getTableDataByIds(ids, tableData);
    let hasUnSaveable = false; // 存在状态错误
    // const saveAbleIds = [];
    const saveAbleDatas = [];
    let unSaveAbleStatus = '';
    let hasUnSaveable2 = false; // 存在下道申请
    datas.forEach(data => {
      if (['0', '2', '3'].includes(data.vcStatus)) {
        hasUnSaveable = true;
        unSaveAbleStatus = data.vcStatus;
      } else if (data.vcType == '0') {
        hasUnSaveable2 = true;
      } else {
        const _data = JSON.parse(JSON.stringify(data));
        _data.vcStatus = '2';
        _data.vcAppersonid = this.userInfo.VC_NUMBER;
        _data.vcAppersonname = this.userInfo.VC_NAME;
        _data.vcAppdate = this.datePipe.transform(new Date(), 'yyyy-MM-dd HH:mm:ss');
        if (_data.dtCodedate) {
          _data.dtCodedate = this.datePipe.transform(_data.dtCodedate, 'yyyy-MM-dd');
        }
        saveAbleDatas.push(_data);
      }
    });
    if (hasUnSaveable) {
      if (!saveAbleDatas.length) {
        this.msg.warning(`勾选的条目属于${this.status[unSaveAbleStatus] || '未定义'}状态，您不可签发此状态的条目`);
        return;
      } else {
        this.msg.warning(`勾选的条目中存在${this.status[unSaveAbleStatus] || '未定义'}状态，此状态的条目将被略过`);
      }
    }
    if (hasUnSaveable2) {
      if (!saveAbleDatas.length) {
        this.msg.warning(`勾选的条目进行了或者处于下道申请状态，您不可签发此状态的条目`);
        return;
      } else {
        this.msg.warning(`勾选的条目进行了或者处于下道申请状态，此状态的条目将被略过`);
      }
    }
    this.qianfaOk(saveAbleDatas);
  }

  editCancel() {
    this.editVisible = false;
  }

  editModal(row) {
    this.editVisible = true;
    this.shouldEdit = false;
    this.editData = JSON.parse(JSON.stringify(row));
    if (this.editData.dtCodedate) {
      this.editData._dtCodedate = this.editData.dtCodedate;
    }
    if (this.editData.dtCodetime) {
      const times = this.editData.dtCodetime.split(' ')[1];
      const _times = times.split(':');
      const _date = new Date();
      _date.setHours(_times[0]);
      _date.setMinutes(_times[1]);
      this.editData._dtCodetime = _date;
    }
  }

  editOk() {
    const param = { ...this.editData };
    if (param._dtCodetime) {
      param.dtCodetime = this.datePipe.transform(param._dtCodetime, 'yyyy-MM-dd HH:mm:ss');
    }
    if (param._dtCodedate) {
      param.dtCodedate = this.datePipe.transform(param._dtCodedate, 'yyyy-MM-dd');
    }
    if (this.userInfo.N_LEVEL == 50) {
      if (param.vcReqpersonid) {
        param.vcReqpersonname = this.getNameFromSelect(param.vcReqpersonid, this.slrList);
      }
    }
    let optName = '';
    if (this.editData.vcStatus == '1') {// 申请 1
      optName = '申请';
    } else if (this.editData.vcStatus == '2') {// 签发 2
      optName = '签发';
    }
    param.vcStatus = '1';
    this.removePrivateField(param);
    const url = environment.project + '/ymTTempworkinfo/update';
    this.http.post(url, param).subscribe((res: any) => {
      if (res.msg === 'Ok') {
        this.msg.success(optName + '成功', { nzDuration: 1000 });
        this.readyload(this.pageIndexTable, this.selectedValue);
        this.editVisible = false;
      } else {
        this.msg.error(optName + '失败', { nzDuration: 1000 });
      }

    });
  }

  qianfaOk(arr) {
    this.modalService.confirm({
      nzTitle: `<i>确认</i>`,
      nzWidth: '600',
      nzContent: `<b>确认签发吗?</b>`,
      nzOnOk: () => {
        const url = environment.project + '/ymTTempworkinfo/updateBatch';
        this.http.post(url, arr).subscribe((res: any) => {
          if (res.msg === 'Ok') {
            this.msg.success('签发' + '成功', { nzDuration: 1000 });
            this.readyload(this.pageIndexTable, this.selectedValue);
          } else {
            this.msg.error('签发' + '失败', { nzDuration: 1000 });
          }
        });
      }
    });

  }

  delCheck() {
    const tableData = this.tableData;
    const tableDataIds = tableData.map(data => data.nId);
    if (!tableData.length) {
      this.msg.warning(`当前无可操作数据`);
      return;
    }
    const datas = tableData.filter(data => data.checked);
    if (!datas.length) {
      this.msg.warning(`请勾选条目进行删除操作`);
      return;
    }
    let hasUnSaveable = false;
    let hasUnSaveable2 = false;
    let hasUnSaveable3 = false;
    const saveAbleIds = [];
    // const saveAbleStatus = [];
    let unSaveAbleStatus = '';
    datas.forEach(data => {
      // if (this.userInfo.N_LEVEL == 10) {
      if (data.vcStatus == '2') {
        hasUnSaveable = true;
        unSaveAbleStatus = data.vcStatus;
      } else if (data.vcType == '0') {
        hasUnSaveable2 = true;
      } else {
        if (!this.selfCheck(data)) {
          hasUnSaveable3 = true;
          return;
        }
        saveAbleIds.push(data.nId);
        // saveAbleStatus.push(data.vcStatus);
      }
    });
    // if (this.userInfo.N_LEVEL == 10) {
    if (hasUnSaveable) {
      if (!saveAbleIds.length) {
        this.msg.warning(`勾选的条目属于${this.status[unSaveAbleStatus] || '未定义'}状态，您不可删除此状态的条目`);
        return;
      } else {
        this.msg.warning(`勾选的条目中存在${this.status[unSaveAbleStatus] || '未定义'}状态，此状态的条目将被略过`);
      }
    }
    // }
    if (hasUnSaveable2) {
      if (!saveAbleIds.length) {
        this.msg.warning(`勾选的条目进行了或者处于下道申请状态，您不可删除此状态的条目`);
        return;
      } else {
        this.msg.warning(`勾选的条目存在进行了或者处于下道申请的条目，此类条目将被略过`);
      }
    }
    // if (this.userInfo.N_LEVEL == 10) {
    if (hasUnSaveable3) {
      if (!saveAbleIds.length) {
        this.msg.warning(`您只能操作执行部门为${this.userInfo.VC_ORG$NAME}的条目`);
        return;
      } else {
        this.msg.warning(`勾选的条目存在执行部门为其他部门的条目，此类条目将被略过`);
      }
    }
    // }
    saveAbleIds.length > 0 ? this.deleteOk(saveAbleIds) : this.refreshStatus();
  }

  deleteOk(saveAbleIds) {
    this.modalService.confirm({
      nzTitle: `<i>确认</i>`,
      nzWidth: '600',
      nzContent: `<b>确认删除吗?</b>`,
      nzOnOk: () => {
        const url = environment.project + '/ymTTempworkinfo/deleteBatch';
        this.http.post(url, saveAbleIds).subscribe((res: any) => {
          if (res.msg === 'Ok') {
            this.msg.success('删除' + '成功', { nzDuration: 1000 });
            this.readyload(this.pageIndexTable, this.selectedValue);
          } else {
            this.msg.error('删除失败', { nzDuration: 1000 });
          }
        });
      }
    });
  }

  /**
   * 下道
   * 如果是调度，不受申请部门的限制
   * 如果是工区，不可下道调度的条目
   */
  xiadaoCheck() {
    const tableData = this.tableData;
    if (!tableData.length) {
      this.msg.warning(`当前无可操作数据`);
      return;
    }
    const datas = tableData.filter(data => data.checked);
    // const ids = this.getCheckIds(this.mapOfCheckedId);
    if (!datas.length) {
      this.msg.warning(`请勾选条目进行下道申请操作`);
      return;
    }
    if (datas.length > 1) {
      this.msg.warning(`最多勾选一个条目进行下道申请操作`);
      return;
    }
    // const datas = this.getTableDataByIds(ids, this.tableData);
    let hasUnSaveable = false;
    let hasUnSaveable2 = false;
    let hasUnSaveable3 = false;
    const saveAbleDatas = [];
    let unSaveAbleStatus = '';
    datas.forEach(data => {
      if (data.vcStatus != '2') {
        hasUnSaveable = true;
        unSaveAbleStatus = data.vcStatus;
      } else if (data.vcType == '0') {
        hasUnSaveable2 = true;
      } else {
        const _data = JSON.parse(JSON.stringify(data));
        if (this.userInfo.N_LEVEL == 10) {
          if (!this.selfCheck(data)) {
            hasUnSaveable3 = true;
            return;
          }
        }
        delete _data.nId;
        _data.vcReqtype = '1';
        _data.vcStatus = '2';
        _data.dtCodetime = this.datePipe.transform(new Date(), 'yyyy-MM-dd HH:mm:ss');
        if (_data.vcCodeinfo) {
          _data.vcCodeinfo += ' 作业完毕已下道';
        } else {
          _data.vcCodeinfo = ' 作业完毕已下道';
        }
        if (_data.vcCodenum) {
          const index1 = _data.vcCodenum.indexOf('(');
          const index2 = _data.vcCodenum.indexOf(')');
          const num = _data.vcCodenum.substr(index1 + 1, index2 - index1 - 1);
          _data.vcCodenum = _data.vcCodenum.replace(`(${num})`, `(${+num + 1})`);
        }
        _data.vcType = '0'; // 不可修改
        _data.dtCodedate = this.datePipe.transform(_data.dtCodedate, 'yyyy-MM-dd');
        saveAbleDatas.push(_data);
      }
    });
    if (hasUnSaveable) {
      if (!saveAbleDatas.length) {
        this.msg.warning(`勾选的条目存在${this.status[unSaveAbleStatus] || '未定义'}状态，您不可申请下道此状态的条目`);
        return;
      } else {
        this.msg.warning(`勾选的条目中存在${this.status[unSaveAbleStatus] || '未定义'}状态，此状态的条目将被略过`);
      }
    }
    if (hasUnSaveable2) {
      if (!saveAbleDatas.length) {
        this.msg.warning(`勾选的条目进行了或者处于下道申请状态，您不可下道申请此状态的条目`);
        return;
      } else {
        this.msg.warning(`勾选的条目存在 进行了或者处于 下道申请状态的条目，此状态的条目将被略过`);
      }
    }
    if (hasUnSaveable3) {
      if (this.userInfo.N_LEVEL == 10) {
        if (!saveAbleDatas.length) {
          this.msg.warning(`您只能操作执行部门为${this.userInfo.VC_ORG$NAME}的条目`);
          return;
        } else {
          this.msg.warning(`勾选的条目存在执行部门为其他部门的条目，此类条目将被略过`);
        }
      }
    }

    const _data_edit = JSON.parse(JSON.stringify(datas[0]));
    _data_edit.vcType = '0'; // 不可修改
    this.xiadaoOk(saveAbleDatas, _data_edit);

  }

  xiadaoOk(saveAbleDatas, data_edit) {
    this.modalService.confirm({
      nzTitle: `<i>确认</i>`,
      nzWidth: '600',
      nzContent: `<b>确认进行下道申请吗?</b>`,
      nzOnOk: () => {
        const url1 = environment.project + '/ymTTempworkinfo/add';
        const url2 = environment.project + '/ymTTempworkinfo/update';
        const addOb = this.http.post(url1, saveAbleDatas[0]);
        const editOb = this.http.post(url2, data_edit);
        forkJoin(addOb, editOb)
          .subscribe((resArr: any) => {
            let isOk = true;
            resArr.forEach((res: any) => {
              if (res.msg != 'Ok') {
                isOk = false;
              }
            });
            if (isOk) {
              this.msg.success('下道申请' + '成功', { nzDuration: 1000 });
              this.readyload(this.pageIndexTable, this.selectedValue);
            } else {
              this.msg.error('下道申请' + '失败', { nzDuration: 1000 });
            }
          });
      }
    });
  }

  // 加载当前列表
  readyload(page, limit) {
    this.tableLoading = true;
    const param: any = {};
    const dataurl = environment.project + '/ymTTempworkinfo/query?page=' + page + '&limit=' + limit;
    if (this.queryParam._sDate) {
      param.sDate = this.datePipe.transform(this.queryParam._sDate, 'yyyy-MM-dd');
    }
    if (this.queryParam._eDate) {
      param.eDate = this.datePipe.transform(this.queryParam._eDate, 'yyyy-MM-dd');
    }

    this.http.get(dataurl, param).subscribe((res: any) => {
      this.tableLoading = false;
      res.data.forEach(row => {
        if (row.dtDate) {
          row._dtDate = this.datePipe.transform(row.dtDate, 'yyyy-MM-dd');
        }
        if (row.vcStatus) {
          row._vcStatus = this.status[row.vcStatus] || '';
        }
      });
      this.tableData = res.data;
      this.pageTotal = res.count;
      this.refreshStatus();
    });
  }


  formatTreeNodes(nodes) {
    if (nodes.length) {
      nodes.forEach(node => {
        node.key = node.id || '';
        node.title = node.text || '';
        if (node.children && node.children.length) {
          this.formatTreeNodes(node.children);
          node.isLeaf = false;
        } else {
          node.isLeaf = true;
        }
      });
    }
  }

  removePrivateField(param) {
    Object.keys(param).forEach(key => {
      if (key.indexOf('_') == 0) {
        delete param[key];
      }
    });
  }

  addModal() {
    this.addVisible = true;
    this.shouldEdit = false;
    this.addData = {};
    this.addData._dtCodedate = new Date();
    this.addData._dtCodetime = new Date();
    if (this.userInfo.N_LEVEL == 10) {
      this.addData.vcReqdepname = this.userInfo.VC_ORG$NAME;
      this.addData.vcReqdep = this.userInfo.VC_ORG$ID;
      this.addData.vcReqpersonname = this.userInfo.VC_NAME;
      this.addData.vcReqpersonid = this.userInfo.VC_NUMBER;
    }
    this.addData.vcCodeinfo = `自接令时起准许 XX 车间 XX 信号工区 XXX、XXX 在 XX 站进行 XX、XX 设备检查作业。`;
    this.addData.vcCoderequ = `1.室内防护人员 XXX 及时掌握 XXX 站列车运行情况，有车及时通知作业人员下道避车。` +
      `\n2.室外防护人员 XXX 及时回复室内防护人员，并及时通知下道避车，遇到特殊情况联系中断时，` +
      `必须按有车通过的要求通知下道避车，做好“三控”措施`;
  }

  addCancel() {
    this.addVisible = false;
  }

  handleOk(type: string) {
    const se = this.shouldEdit;
    const param = { ...(se ? this.detailData : this.addData) };
    if (param._dtCodetime) {
      param.dtCodetime = this.datePipe.transform(param._dtCodetime, 'yyyy-MM-dd HH:mm:ss');
    }
    if (param._dtCodedate) {
      param.dtCodedate = this.datePipe.transform(param._dtCodedate, 'yyyy-MM-dd');
    }
    if (this.userInfo.N_LEVEL == 50) {
      if (param.vcReqpersonid) {
        param.vcReqpersonname = this.getNameFromSelect(param.vcReqpersonid, this.slrList);
      }
    }
    if (type === 'add') {
      param.vcStatus = '0';
      param.vcType = '1';
    }
    this.removePrivateField(param);
    const url = `${environment.project}/ymTTempworkinfo/${type}`;
    param.vcReqpersonname = param.vcReqpersonid;
    this.http.post(url, param).subscribe((res: any) => {
      if (res.msg === 'Ok') {
        this.msg.success(`${se ? '修改' : '新增'}成功`, { nzDuration: 1000 });
        this.readyload(this.pageIndexTable, this.selectedValue);
        if (se) this.detailVisible = false; else this.addVisible = false;
      } else {
        this.msg.error(`${se ? '修改' : '新增'}失败`, { nzDuration: 1000 });
      }
    });
  }

  dblclick(row) {
    this.detailData = JSON.parse(JSON.stringify(row));
    this.detailVisible = true;
    this.shouldEdit = this.userInfo.N_LEVEL === 50 || ["0", "3"].includes(row.vcStatus);
    if (this.detailData.dtCodedate) {
      this.detailData._dtCodedate = this.detailData.dtCodedate;
    }
    if (this.detailData.dtCodetime) {
      const times = this.detailData.dtCodetime.split(' ')[1];
      const _times = times.split(':');
      const _date = new Date();
      _date.setHours(_times[0]);
      _date.setMinutes(_times[1]);
      this.detailData._dtCodetime = _date;
    }
  }

  detailCancel() {
    this.detailVisible = false;
  }

  cjChange(value) {
    if (this.cjList.length) {
      if (!value) {
        this.cjList_filter = this.cjList;
      } else {
        this.cjList_filter = this.cjList.filter(el => el.opName.includes(value));
      }
    }
  }

  gqChange(value) {
    if (this.gqList.length) {
      if (!value) {
        this.gqList_filter = this.gqList;
      } else {
        this.gqList_filter = this.gqList.filter(el => el.opName.includes(value));
      }
    }
  }

  gqClick(type) {
    if (type == 'add') {
      this.getWorkarea(this.addData._cj, type);
    } else if (type == 'edit') {
      this.getWorkarea(this.shouldEdit ? this.detailData._cj : this.editData._cj, type);
    }
  }

  getWorkarea(workshopId, type) {
    if (!workshopId) {
      return;
    }
    this.apiService.getgongquByCjId(workshopId).subscribe(res => {
      let _data;
      if (typeof res == 'string') {
        _data = JSON.parse(res);
      } else {
        _data = res;
      }
      let delIndex;
      for (let i = 0; i < _data.length; i++) {
        const el = _data[i];
        if (!el.opValue) {
          delIndex = i;
        }
      }
      _data.splice(delIndex, 1);
      this.gqList = _data;
      this.gqList_filter = _data;
    });
  }

  getWorkshop() {
    this.apiService.getAllChejian('1').subscribe(res => {
      let _data;
      if (typeof res == 'string') {
        _data = JSON.parse(res);
      } else {
        _data = res;
      }
      let delIndex;
      for (let i = 0; i < _data.length; i++) {
        const el = _data[i];
        if (!el.opValue) {
          delIndex = i;
        }
      }
      _data.splice(delIndex, 1);
      this.cjList = _data;
      this.cjList_filter = _data;
    });
  }

  showDevSelect(type, content) {
    const data = this[`${type}Data`];
    data._gq = '';
    data._cj = '';
    this[`showCjGq_${type}`] = true;
    this.modalService.confirm({
      nzTitle: `<i>部门选择</i>`,
      nzWidth: '400',
      nzContent: content,
      nzOnOk: () => {
        if (data._gq) {
          data.vcReqdep = data._gq;
          data.vcReqdepname = this.getNameFromSelect(data._gq, this.gqList);
        } else {
          this.msg.warning('请选择工区');
          return false;
        }
      }
    });
  }

  getNameFromSelect(id, selectList) {
    for (const item of selectList) {
      if (item.opValue == id) {
        return item.opName;
      }
    }
    return;
  }

  getPeople(func, id) {
    const url = environment.apiBase + '/csmis/person/getOrgPersonListById.jwt?orgId=' + id;
    this.http.get(url).subscribe((res: any) => {
      if (func) {
        func(res);
      }
    });
  }

  slrChange(type) {
    // if (this.slrList.length) {
    //   if (!value) {
    //     this.slrList_filter = this.slrList;
    //   } else {
    //     this.slrList_filter = this.slrList.filter(el => el.opName.includes(value));
    //   }
    // } else {
    if (!this[`${type}Data`].vcReqdep) {
      this.msg.warning(`请先选择受令执行部门!`);
      return;
    }
    this.getPeople(res => this.slrList_filter = this.slrList = res
      , this[`${type}Data`].vcReqdep);
  }
}
